package org.apache.ocean;

import java.util.*;
import java.lang.reflect.*;
import java.util.logging.*;

/**
 *
 * @author  administrator
 * @version
 */
public class FieldUtil {
  public static Logger log = Logger.getLogger(FieldUtil.class.getName());
  private static Map<String, Field[]> fieldMap = new HashMap<String, Field[]>(30);

  public static boolean setFieldValue(Object object, String fieldName, Object value) throws Exception {
    try {
      if (value == null) {
        return false;
      }
      Field field = getField(object.getClass(), fieldName);
      if (field != null) {
        field.setAccessible(true);
        field.set(object, value);
        return true;
      } else {
        return false;
      }
    } catch (Exception ex) {
      throw new Exception("fieldName: " + fieldName + " value: " + value, ex);
    }
  }

  public static Object getFieldValue(String fieldName, Object object) throws Exception {
    //try {
    Field field = getField(object.getClass(), fieldName);
    if (field == null) {
      return null;
    }
    field.setAccessible(true);
    return field.get(object);
  //} catch (Exception ex) {
  //  log.log(Level.SEVERE, "", ex);
  //  return null;
  //}
  }

  public static Field getField(Class clazz, String fieldName) {
    Field[] fields = getFields(clazz);
    for (int x = 0; x < fields.length; x++) {
      if (fields[x].getName().equalsIgnoreCase(fieldName)) {
        return fields[x];
      }
    }
    return null;
  }

  public static Field[] getFields(Class clazz) {
    Field[] fields = (Field[])fieldMap.get(clazz.getName());
    if (fields != null) {
      return fields;
    }
    List<Field> vector = new ArrayList<Field>(10);
    getFields(clazz, vector);

    fields = new Field[vector.size()];
    for (int x = 0; x < fields.length; x++) {
      fields[x] = (Field)vector.get(x);
    }
    fieldMap.put(clazz.getName(), fields);
    return fields;
  }

  public static void getFields(Class clazz, List<Field> vector) {
    Field[] fields = clazz.getDeclaredFields();
    for (int x = 0; x < fields.length; x++) {
      int modifiers = fields[x].getModifiers();
      if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers) && !Modifier.isFinal(modifiers)) {
        if (!vector.contains(fields[x])) {
          vector.add(fields[x]);
        }
      }
    }
    Class superClass = clazz.getSuperclass();
    if (superClass != null) {
      getFields(superClass, vector);
    }
  }
}
